<?php 
//verander de 'taal' van php
//standaard use php english but if your want you can edit it to any other language. More info can be found at http://www.php.net
//setlocale(LC_TIME, 'NL_nl');
//OS: Windows
/* Set locale to Dutch */
//setlocale(LC_ALL, 'nld_nld');

setlocale(LC_ALL, 'nl_NL');

date_default_timezone_set('Europe/Amsterdam'); 
$timezone = new DateTimeZone('Europe/Amsterdam'); 

require_once 'config.inc.php';
require_once 'mysql.login.inc.php';
require_once 'common.classes.php';

session_start();

$session_id = session_id();
$link = false;
$ip_adres = str_replace("'","\"",$_SERVER['REMOTE_ADDR'] ."/". $_SERVER['USERNAME']);
$email = isset($_SESSION["EMAIL"]) ? $_SESSION["EMAIL"] : null;
$name1 = isset($_SESSION["NAME1"]) ? $_SESSION["NAME1"] : null;
$name2 = isset($_SESSION["NAME2"]) ? $_SESSION["NAME2"] : null;
$gender = isset($_SESSION["GENDER"]) ? $_SESSION["GENDER"] : null;
$tel_number = isset($_SESSION["TEL_NUMBER"]) ? $_SESSION["TEL_NUMBER"] : null;
$kenteken_auto = isset($_SESSION["KENTEKEN_AUTO"]) ? $_SESSION["KENTEKEN_AUTO"] : null; 
$company_code = isset($_SESSION["COMPANY_CODE"]) ? $_SESSION["COMPANY_CODE"] : null;
$location_code = isset($_SESSION["LOCATION_CODE"]) ? $_SESSION["LOCATION_CODE"] : null;
$logged_out = isset($_SESSION["LOGGED_OUT"]) ? $_SESSION["LOGGED_OUT"] : false;
$direct = isset($_REQUEST["DIRECT"]) ? $_REQUEST["DIRECT"] : false;

$service_code = null;
$menuSelected = null;
$showNameDialog = 0;
$timePeriod = 20;
$subMenuSelected = null;
$cookie_id = initcookie();
$logged_in = (!empty($email) && $logged_out == false);
$user_name = (isset($name1) && $name1 != null) ? $name1." (".$email.") " : $email;

$msg = null;
$error = null;
$success = false;
$generalErrorMessage = "Er is een onverwachte fout opgetreden. Probeer het opnieuw of neem contact op met je beheerder!";
 
$aanhefArr = Array();
$aanhefArr[0] = "Kies aanhef";
$aanhefArr[1] = "De heer";
$aanhefArr[2] = "Mevrouw";
$aanhefArr[3] = "Familie";
$aanhefArr[4] = "Bedrijf";

function conn() {
	global $link;	
	global $host;
	global $username;
	global $password;
	global $database;
	
	$link = mysql_connect($host, $username, $password);

	if (!$link) {die('Could not connect: ' . mysql_error());}
	if (!mysql_select_db($database)) {die('Could not select database: ' . mysql_error());}
	
	return $link;
}

function close() {
  global $link;
	
  if( $link != false ) mysql_close($link);
  $link = false;
}

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        return ob_get_clean();
    }
    return false;
}

function dropdown($arr,$name,$selectedValue,$styleClass) {
  $min = ($styleClass == "required") ? 1 : 0;
    
  $sel = ' selected style="color: #BBBBBB" ';
  $str = "";  
  $str .= "<select name=\"$name\" min=\"$min\" class=\"$styleClass\" >";
  foreach ($arr as $i => $value) {
    $str .= "<option value=\"$i\" ";
    if ($selectedValue == $i) $str .= $sel;
    $str .= ">$value</option>";  
  }
  $str .= "</select>";
  unset($value); // break the reference with the last element
  return $str;
}

function getReqSesValue($name) {
  if (isset($_REQUEST[$name])) { 
    $_SESSION[$name] = $_REQUEST[$name];
    return $_REQUEST[$name];
  }  
  else if (isset($_SESSION[$name])) { 
    return $_SESSION[$name];
  } 
  else { 
    return ""; 
  }
}

function getReqSesCooValue($name) {
  $cookieIsSet = true;
  $value = getReqSesValue($name);
  
  if (!isset($_COOKIE[$name]) || $_COOKIE[$name] == null || $_COOKIE[$name] == "") {
    $cookieIsSet = false;
  } else if ($value == "") {
    $value = $_COOKIE[$name];
  }

  if ($value != "") {
    $_COOKIE[$name] = $value;
  }
  
  return $value; 
}

function curPageURL() {
  $pageURL = 'http';
  if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
  if ($_SERVER["SERVER_PORT"] != "80") {
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  } else {
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  }
  return $pageURL;
}

function initcookie() {
	global $link;
	global $ip_adres;
	global $cookie_id;
	global $email;
	global $name1;
	global $gender;
  global $company_code;
  
  $cookieIsSet = null;
  
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		$cookie_id = $_COOKIE["PERSPEKT_COOKIE"];
    return $cookie_id;
  }

	if (!isset($_COOKIE["PERSPEKT_COOKIE"]) || empty($_COOKIE["PERSPEKT_COOKIE"])) {
    $cookieIsSet = false;
	} else {
    $cookieIsSet = true;
		$cookie_id = $_COOKIE["PERSPEKT_COOKIE"];
		conn();
		$sql = "SELECT ID, EMAIL FROM COOKIES WHERE ID = '$cookie_id'";
		$result = mysql_query($sql);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    if (!isset($row["ID"]) || empty($row["ID"])) {
      $cookieIsSet = false;
    } else if (!isset($email) || empty($email)) {
      $email = $row["EMAIL"];
        // keep in session
      $_SESSION["EMAIL"] = $email;
    }
    if (!empty($email) && empty($name1)) {
      $sql = "SELECT ID, NAME1, GENDER FROM CUSTOMERS WHERE EMAIL = '".mysql_escape($email)."'";
      $result = mysql_query($sql);
      $row = mysql_fetch_array($result, MYSQL_ASSOC);
      if (isset($row["ID"]) && $row["ID"] != null) {
        $name1 = $row["NAME1"];
        $gender = $row["GENDER"];
        // keep in session
        $_SESSION["NAME1"] = $name1;
        $_SESSION["GENDER"] = $gender;
      }
    }
    close();
	}

  // insert and set cookie  
  if (!$cookieIsSet) {
		conn();
		$sql = "INSERT INTO COOKIES (IP_ADRES, EMAIL) VALUE ('$ip_adres', '".mysql_escape($email)."')";
		$result = mysql_query($sql);
		if (!$result) {die('Could not exec query: ' . mysql_error());}
		$cookie_id = mysql_insert_id();
		close();
		setcookie ("PERSPEKT_COOKIE", $cookie_id, time() + 60*60*24*700); // 700 dagen
  }
  
  // retrieve company code     
  if (empty($company_code) && !empty($email)) {
    // 
    $extensie = strtoupper(substr($email,strpos($email,"@")+1,strlen($email)-strpos($email,"@")-1));
    //
    conn();
    $sql = "SELECT UPPER(c.CODE) AS CODE ";
    $sql .= "FROM COMPANIES c ";
    $sql .= "INNER JOIN EMAILS e ON e.COMPANY_CODE = c.CODE ";
    $sql .= "WHERE ( UPPER(e.EMAIL) = UPPER('".mysql_escape($extensie)."') ";
    $sql .= "     OR UPPER(e.EMAIL) = UPPER('".mysql_escape($email)."') ) ";
    //echo $sql;
    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query sql: ' . mysql_error());}
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    $company_code = (!isset($row["CODE"]) || $row["CODE"] == null) ? "" : $row["CODE"];
    $_SESSION["COMPANY_CODE"] = $company_code;
    close();
  }
    
	return $cookie_id;
}

function checkReservationsTable() {
  global $schedule_id;
  global $reservation_id;
  global $reservation_confirmed;
  global $reservation_date;
  global $email;
  global $prev_date_is_reserved;
  global $prev_date_is_reserved_by_sign_in;
  global $reserved;
  global $reserved_by_sign_in;
  global $next_date_is_reserved;
  global $next_date_is_reserved_by_sign_in;
  
  // previous date
  $prev_date = subMinutes($reservation_date, 20);
  //$prev_date = clone $reservation_date; 
  //$prev_date->sub(new DateInterval('PT20M'));
  $prev_date_compare = $prev_date->format('Y-m-d H:i');
  //echo $prev_date_compare."<br />";

  $sql = "";
  $sql .= "SELECT ID, SIGN_IN_EMAIL, CAST(CONFIRMED AS unsigned int) CONFIRMED ";
  $sql .= "FROM RESERVATIONS ";
  $sql .= "WHERE DATE_FORMAT(START,'%Y-%m-%d %H:%i') = '$prev_date_compare' ";
  $sql .= "AND SCHEDULE_ID = '$schedule_id'";
  //$sql .= "AND SIGN_IN_EMAIL = '$email'";
  //echo "<br />".$sql."<br />";
  
  conn();
  $result = mysql_query($sql);
  if (!$result) {die('Could not exec query: ' . mysql_error());}
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  if (isset($row["ID"]) && $row["ID"] != null) 
  {
    //echo "0";
    $prev_date_is_reserved = true;
    $prev_date_is_reserved_by_sign_in = (strtoupper($row["SIGN_IN_EMAIL"]) == strtoupper($email)) ? true : false;
  } 
  else 
  {
    $prev_date_is_reserved = false;
    $prev_date_is_reserved_by_sign_in = false;
  }

    // current date
  $current_date_compare = $reservation_date->format('Y-m-d H:i');

  $sql = "";
  $sql .= "SELECT ID, SIGN_IN_EMAIL, CAST(CONFIRMED AS unsigned int) CONFIRMED ";
  $sql .= "FROM RESERVATIONS ";
  $sql .= "WHERE DATE_FORMAT(START,'%Y-%m-%d %H:%i') = '$current_date_compare' ";
  $sql .= "AND SCHEDULE_ID = '$schedule_id'";
  //$sql .= "AND SIGN_IN_EMAIL = '$email'";
  //echo $sql;
 
  $result = mysql_query($sql);
  if (!$result) {die('Could not exec query: ' . mysql_error());}
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  if (isset($row["ID"]) && $row["ID"] != null) 
  {
    //echo $sql;
    $reservation_id = $row["ID"];
    $reservation_confirmed = ($row["CONFIRMED"] == 1) ? true : false;
    //echo $row["CONFIRMED"];
    $reserved = true;
    $reserved_by_sign_in = (strtoupper($row["SIGN_IN_EMAIL"]) == strtoupper($email)) ? true : false;
  } 
  else 
  {
    $reservation_id = null;
    $reservation_confirmed = false;
    $reserved = false;
    $reserved_by_sign_in = false;
  }

  // next date
  $next_date = addMinutes($reservation_date, 20);
  //$next_date = clone $reservation_date; 
  //$next_date->add(new DateInterval('PT20M'));
  $next_date_compare = $next_date->format('Y-m-d H:i');
  //echo $next_date_compare."<br />";
  
  $sql = "";
  $sql .= "SELECT ID, SIGN_IN_EMAIL, CONFIRMED ";
  $sql .= "FROM RESERVATIONS ";
  $sql .= "WHERE DATE_FORMAT(START,'%Y-%m-%d %H:%i') = '$next_date_compare' ";
  $sql .= "AND SCHEDULE_ID = '$schedule_id'";
  //$sql .= "AND SIGN_IN_EMAIL = '$email'";
  //echo $sql;
  
  $result = mysql_query($sql);
  if (!$result) {die('Could not exec query: ' . mysql_error());}
  close();
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  if (isset($row["ID"]) && $row["ID"] != null) 
  {
    $next_date_is_reserved = true;
    $next_date_is_reserved_by_sign_in = (strtoupper($row["SIGN_IN_EMAIL"]) == strtoupper($email)) ? true : false;
  } 
  else 
  {
    $next_date_is_reserved = false;
    $next_date_is_reserved_by_sign_in = false;
  }
  
}

function deleteOldReservations() {

  conn();

  $sql = "DELETE ";
  $sql .= "FROM RESERVATIONS_CAR_WASH ";
  $sql .= "WHERE RESERVATION_ID IN ( ";
  $sql .= "  SELECT ID ";
  $sql .= "  FROM RESERVATIONS ";
  $sql .= "  WHERE CAST(CONFIRMED AS unsigned int) = 0 ";
  $sql .= "  AND ADDTIME(CREATE_DATE, '00:20:00') < NOW( ) ";
  $sql .= ") ";
  $result = mysql_query($sql);
  if (!$result) {die('Could not exec query deleteOldReservations 1: ' . mysql_error());}
  
  $sql = "DELETE ";
  $sql .= "FROM RESERVATIONS ";
  $sql .= "WHERE CAST(CONFIRMED AS unsigned int) = 0 ";
  $sql .= "AND ADDTIME(CREATE_DATE, '00:20:00') < NOW( ) ";
  $result = mysql_query($sql);
  if (!$result) {die('Could not exec query deleteOldReservations 2: ' . mysql_error());}
  
  close();
}

function koppelCookie($persoon_id) {
  global $ip_adres;
  
  conn();
  
  $isSet = true;
  $sqlIsSet = "SELECT ID FROM COOKIES WHERE IP_ADRES = '$ip_adres' AND PERSOON_ID = '$persoon_id'";
  $result = mysql_query($sqlIsSet);
  if (!$result) {die('Could not exec query: ' . mysql_error());}
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  if (!isset($row["ID"]) || $row["ID"] == null) {
    $isSet = false;
  }
    
  if ($isSet == false) {
    $sqlInsert = "INSERT INTO COOKIES (IP_ADRES, PERSOON_ID) VALUE ('$ip_adres','$persoon_id')";
    $result = mysql_query($sqlInsert);
  }
  
  close();
}

function addMinutes($dateObject, $min) {
  global $timezone;

   $tmp = strtotime($dateObject->format('Y-m-d H:i:s'));
   $added = strtotime("+".$min."Min", $tmp);
   $rtnDate = new DateTimeDutch("@".$added, $timezone);
   $rtnDate->setTimezone($timezone); 
   return $rtnDate;
}

function subMinutes($dateObject, $min) {
  global $timezone;

   $tmp = strtotime($dateObject->format('Y-m-d H:i:s'));
   $added = strtotime("-".$min."Min", $tmp);
   $rtnDate = new DateTimeDutch("@".$added, $timezone);
   $rtnDate->setTimezone($timezone); 
   return $rtnDate;
}

function maxTextTo($oms, $max) {
  if (strlen($oms) > $max)
    return substr($oms,0,$max)." ...";
  else 
    return $oms;    
}

function autoWassenPakketSwitch() {
  global $auto_wassen_pakket;
  global $auto_wassen_pakket_nr;
  global $auto_wassen_pakket_desc;
  global $auto_wassen_pakket_price;
  global $auto_wassen_pakket_price_display;
  
  if ($auto_wassen_pakket == "1") {
    $auto_wassen_pakket_nr = "002";
    $auto_wassen_pakket_desc = "Autostomen pakket 1";
    $auto_wassen_pakket_price = "4950";
    $auto_wassen_pakket_price_display = "49,50";
  } else if ($auto_wassen_pakket == "2") {
    $auto_wassen_pakket_nr = "003";
    $auto_wassen_pakket_desc = "Autostomen pakket 2";
    $auto_wassen_pakket_price = "5950";
    $auto_wassen_pakket_price_display = "59,50";
  } else if ($auto_wassen_pakket == "3") {
    $auto_wassen_pakket_nr = "004";
    $auto_wassen_pakket_desc = "Autostomen pakket 3";
    $auto_wassen_pakket_price = "9950";
    $auto_wassen_pakket_price_display = "99,50";
  } else {
    $auto_wassen_pakket_nr = "000";
    $auto_wassen_pakket_desc = "-";
    $auto_wassen_pakket_price = "0000";
    $auto_wassen_pakket_price_display = "0,00";
  }
}

function parseAdText($oms) {
	$rtn = $oms;

  $replace = array("","","","","","","");
  
  $search1a = array("<br>","<strong>","<p>","<h1>","<h2>","<h3>","<h4>");
  $search1b = array("<br/>","</strong>","</p>","</h1>","</h2>","</h3>","</h4>");
  $rtn = str_replace($search1a,$replace,$rtn);
  $rtn = str_replace($search1b,$replace,$rtn);

  $search2a = array("<ul>","<li>","<span>","<div>","<pre>","<b>","<h6>");
  $search2b = array("</ul>","</li>","</span>","</div>","</pre>","</b>","</h6>");
  $rtn = str_replace($search2a,$replace,$rtn);
  $rtn = str_replace($search2b,$replace,$rtn);
	
	return $rtn;
}

function mysql_escape($str) {
  $search = array("\\","\0","\n","\r","\x1a","'",'"');
  $replace = array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
  
  return str_replace($search,$replace,$str);
}

/**
 * Transforms $_SERVER HTTP headers into a nice associative array. For example:
 *   array(
 *       'Referer' => 'example.com',
 *       'X-Requested-With' => 'XMLHttpRequest'
 *   )
 */
function print_request_headers() {
    echo '<table border="1">';

    foreach($_SERVER as $k => $v) {
        echo '<tr><td>'.$k.'</td><td>'.$v.'</td></tr>';
    }
    echo '</table>';
	
	echo gethostbyname($_SERVER['SERVER_NAME']);
}

function dropdown2($result,$name,$selectedValue,$styleClass) {
  $min = ($styleClass == "required") ? 1 : 0;
    
  $sel = ' selected="selected" style="color: #BBBBBB" ';
  $emptyStr = "";  
  
  $str = "";  
  $str .= "<select id=\"$name\" name=\"$name\" min=\"$min\" class=\"$styleClass\" >";
  while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $test = ($selectedValue == $row["CODE"]) ? $sel : $emptyStr;
    $str .= "<option ".$test." value=\"".$row["CODE"]."\">".$row["CODE"]." - ".$row["NAME"]."</option>";
  }   
  $str .= "</select>";
  return $str;
}

?>